package com.peanut.devlibrary.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.TextView;

import com.peanut.baby.R;


/**
 * Created by taransky on 16/5/19.
 */
public class TitleBackTextView extends TextView {
    public static final int NO_DRAWABLE = -1;
    private int 			mDrawableIconHeight;
    private int 			mDrawablePadding;
    public TitleBackTextView(Context context) {
        super(context);
        init(context);
    }

    public TitleBackTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public TitleBackTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    @SuppressLint("InflateParams")
    private void init(Context context){

        mDrawableIconHeight = dip2px(16);
        mDrawablePadding = dip2px(5);
        setTextColor(Color.BLACK);
        setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        setClickable(true);
        setSingleLine(true);
        setPadding(dip2px(10), 0, dip2px(10), 0);
        setBackgroundResource(R.drawable.library_selector_transparent_translucent);
        setGravity(Gravity.CENTER_VERTICAL);
        setCompoundDrawablePadding(mDrawablePadding);
        setBackDrawable(R.drawable.library_button_back_icon_new);



    }

    private int dip2px(float dpValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void setBackDrawable(int resId){
        if(resId == NO_DRAWABLE){
            setCompoundDrawables(null, null, null, null);
        }else{
            try {
               Drawable mBackDrawable = getContext().getResources().getDrawable(resId);
                if(mBackDrawable != null){
                    int width = mBackDrawable.getIntrinsicWidth();
                    int height = mBackDrawable.getIntrinsicHeight();

                    mBackDrawable.setBounds(0, 0, width * mDrawableIconHeight / height, mDrawableIconHeight);
                    setCompoundDrawables(mBackDrawable, null, null, null);
                }

            } catch (Resources.NotFoundException e) {

            }
        }

    };
}
